package com.gwtjs.icustom.utils;

import cn.hutool.core.io.IoUtil;

import com.gwtjs.icustom.pojo.ServerHost;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;

/**
 * <h2>Linux CentOS 7系统指令执行工具,目前仅支持CentOS 7</h2>
 * 
 * @author flash shell脚本调用类
 *
 */
public class ShellUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(ShellUtil.class);
	private Vector<String> stdout;
	// 会话session
	Session session;

	public static void main(String[] args) {
		String cmd = "ls /opt/";
		ShellUtil execute = new ShellUtil("IP", "account", "password", 22);
		// 执行命令
		String result = execute.executeForResult(cmd);
		System.out.println(result);
		execute.close();
	}

	// 输入IP、端口、用户名和密码，连接远程服务器
	public ShellUtil(final ServerHost server) {
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(server.getAccount(), server.getHostIp(), server.getHostPort());
			session.setPassword(server.getPassword());
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect(100000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 输入IP、端口、用户名和密码，连接远程服务器
	public ShellUtil(final String ipAddress, final String username, final String password, int port) {
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(username, ipAddress, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect(100000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int execute(final String command) {
		int returnCode = 0;
		ChannelShell channel = null;
		PrintWriter printWriter = null;
		BufferedReader input = null;
		stdout = new Vector<String>();
		try {
			channel = (ChannelShell) session.openChannel("shell");
			channel.connect();
			input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
			printWriter = new PrintWriter(channel.getOutputStream());
			printWriter.println(command);
			printWriter.println("\nexit");
			printWriter.flush();
			logger.info("The remote command is: ");
			String line;
			while ((line = input.readLine()) != null) {
				stdout.add(line);
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			IoUtil.close(printWriter);
			IoUtil.close(input);
			if (channel != null) {
				channel.disconnect();
			}
		}
		return returnCode;
	}

	// 断开连接
	public void close() {
		if (session != null) {
			session.disconnect();
		}
	}

	// 执行命令获取执行结果
	public String executeForResult(String command) {
		execute(command);
		StringBuilder sb = new StringBuilder();
		for (String str : stdout) {
			sb.append("\n"+str);
		}
		return sb.toString();
	}
	
}
